package org.dtrd.modules.patient.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.util.DateUtils;
import org.dtrd.common.util.StringUtil;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.SystemState;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.doctor.service.IDtrdRlDoctorPatientService;
import org.dtrd.modules.flup.service.IDtrdEntRdFlupAppointmentRecordService;
import org.dtrd.modules.food.entity.bean.EmsGlycemicIndexBean;
import org.dtrd.modules.patient.entity.bean.PatientHomePageInfo;
import org.dtrd.modules.patient.entity.bean.PatientIndexFormInfo;
import org.dtrd.modules.patient.entity.bean.PatientInfo;
import org.dtrd.modules.patient.entity.po.DtrdEntRdPatient;
import org.dtrd.modules.patient.entity.request.PatientAllRequest;
import org.dtrd.modules.patient.entity.request.PatientDoctorRequest;
import org.dtrd.modules.patient.entity.request.PatientIndexRequest;
import org.dtrd.modules.patient.entity.request.PatientRequest;
import org.dtrd.modules.patient.service.IDtrdEntRdPatientService;
import org.dtrd.modules.patient.service.IDtrdRlGroupPatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.Optional;
import java.util.OptionalDouble;

import static org.dtrd.common.constant.CommonConstant.OPERATE_TYPE_QUERY;
import static org.dtrd.config.system.SystemState.ResponseState.STATE_PARAMS_MISSING;

/**
 * @author 萧
 * @date:2021-09-26 11:28 下午
 **/
@RestController
@Slf4j
@RequestMapping(value = {"/patient", "/108/01"})
@Api(tags = "患者信息")
public class PatientController extends BaseController {


    @Autowired
    private IDtrdEntRdPatientService patientService;
    @Autowired
    private IDtrdEntRdFlupAppointmentRecordService appointmentRecordService;
    @Autowired
    private BaseCommonService baseCommonService;
    @Autowired
    private IDtrdRlGroupPatientService groupPatientService;
    @Autowired
    private IDtrdRlDoctorPatientService doctorPatientService;

    @ApiOperation("获取所有患者")
    @PostMapping("/all")
    public Result<?> getAllPatients(@RequestBody PatientAllRequest request) {
        IPage<PatientInfo> page = patientService.getAllPatients(request);
        return Result.OK(page);
    }

    @ApiOperation("创建医患关系")
    @PostMapping("/doctor/bind")
    public Result<?> bindDoctorPatient(@RequestBody PatientDoctorRequest request) {
        boolean result = doctorPatientService.saveOrUpdateDoctorPatientRelation(request.getDoctorId(), request.getPatientId(), Constant.DoctorPatientRelationType.ADD_BY_OMS.getType());
        return result ? Result.OK() : Result.error("绑定失败");
    }

    @ApiOperation("根据患者ID查询患者信息")
    @PostMapping("/query")
    public Result<?> getPatientInfoById(@RequestBody PatientRequest request) {
        if (isIntParamInvalid(request.getPatientId())) {
            return error(STATE_PARAMS_MISSING);
        }
        PatientInfo patientInfo = patientService.selectByPatientId(request.getPatientId());
        return patientInfo == null ? error(SystemState.ResponseState.STATE_NO_RECORD) : Result.OK(patientInfo);
    }

    @ApiOperation("修改患者信息")
    @PostMapping("/update")
    public Result<?> updatePatientInfo(@RequestBody PatientInfo patientInfo) {
        if (isIntParamInvalid(patientInfo.getDataId())) {
            return error(STATE_PARAMS_MISSING);
        }
        boolean result = patientService.updatePatientInfo(patientInfo, false);
        return result ? Result.OK() : error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
    }

    @ApiOperation("小程序登录后同步患者信息")
    @PostMapping("/login/update")
    public Result<?> updateLoginPatientInfo(@RequestBody PatientInfo patientInfo) {
        if (isIntParamInvalid(patientInfo.getDataId())) {
            return error(STATE_PARAMS_MISSING);
        }
        boolean result = patientService.updatePatientInfo(patientInfo, true);
        return result ? Result.OK() : error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
    }

    @ApiOperation("查询企微患者详情")
    @PostMapping("/1080104")
    public Result<?> getQiyeWeixinPatientInfo(@RequestBody PatientRequest request) {
        if (isIntParamInvalid(request.getPatientId())) {
            return error(STATE_PARAMS_MISSING);
        }
        PatientInfo info = patientService.selectByPatientId(request.getPatientId());
        if (info == null) {
            return error(SystemState.ResponseState.STATE_PARAMS_ERROR);
        }
        String groupName = groupPatientService.getGroupName(request.getPatientId());
        info.setServiceName(groupName);
        info.setStatus(appointmentRecordService.getPatientFlupStatus(info.getDataId()));
        return Result.OK(info);
    }


    @ApiOperation(value = "获取患者首页统计数据", response = PatientHomePageInfo.class)
    @GetMapping("1080105")
    public Result<?> getPatientStatisticInfo(
            @ApiParam("患者id") @RequestParam Integer patientId
    ) {
        if (isIntParamInvalid(patientId)) {
            return error(STATE_PARAMS_MISSING);
        }
        PatientHomePageInfo patientHomePageInfo = patientService.getPatientHomePageInfo(patientId);
        String logContent = String.format("获取患者首页统计数据, 患者id: %d", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(patientHomePageInfo);
    }

    @ApiOperation(value = "获取患者首页表格部分信息", response = PatientIndexFormInfo.class)
    @PostMapping("1080106")
    public Result<?> getPatientStatisticFormInfo(@RequestBody PatientIndexRequest request) {
        Integer patientId = request.getPatientId();
        if (patientId == null) {
            return error(STATE_PARAMS_MISSING);
        }
        handleRequest(request);
//        PatientIndexFormInfo formInfo = patientService.getPatientIndexFormInfo(request);
        PatientIndexFormInfo formInfo = patientService.getPatientIndexFormInfoV3(request);
        String logContent = String.format("获取患者首页表格部分信息, 患者id %d, 查询日期: %s ~ %s",
                patientId,
                DateUtil.formatDate(request.getStartDate()),
                DateUtil.formatDate(request.getEndDate()));
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(formInfo);
    }

    private void handleRequest(PatientIndexRequest request) {
        Integer type = request.getType();
        Date now = DateUtils.getDateYMD();
        request.setEndDate(now);
        DateTime beginOfMonth = DateUtil.beginOfMonth(now);
        switch (type) {
            case 1:
                request.setStartDate(DateUtil.offset(now, DateField.DAY_OF_MONTH, -14));
                break;
            case 2:
                request.setStartDate(DateUtil.offset(now, DateField.DAY_OF_MONTH, -30));
                break;
            case 3:
                request.setStartDate(DateUtil.offset(beginOfMonth, DateField.MONTH, -2));
                break;
            default:
                break;
        }
    }

}
